﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;
using FrameworkManapro.WebUI;
using GMAC.ReportingSystem.Business.Components;
using GMAC.ReportingSystem.Business.Entities.Others;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class HistoricRePurchases : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            
            Initialize();
            
            ValidateSecurity();
            
        }

        #endregion

        ////////////////////////////////////////////////////////////////

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new HistoricRePurchaseComponent();

                var historicRePurchase = ReadHistoricRePurchase();

                bc.Create(historicRePurchase);

                var audit = new FrameworkManapro.Audit.Audit<HistoricRePurchase>
                {
                    EntityKey = historicRePurchase.LiquidationYear.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = historicRePurchase,
                    UserId    = ((User)Session["User"]).UserID
                };

                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<HistoricRePurchase>(audit);
                
                auditDAC.InsertAudit();
                
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Historic Re-Purchase was successfully saved.", null);
                
                popupExtenderMessage.Show();
                
                this.PagingControl.TotalRecords = Search();
                
                Search();
                
                ClearFields();

                UpdateAvailableYears();
            }
            catch (Exception ex)
            {
                var message = (ex.Message == "DuplicateYearException") ? "There is already a Historic Re-Purchase for this Year." : "The Historic Re-Purchase could not be saved";

                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Historic RePurchase", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, message, null);
                popupExtenderMessage.Show(); ;
            }
        }

        //-----------------------------------------------------
        
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible  = true;
            
            var bc = new HistoricRePurchaseComponent();
            
            try
            {
                var historicRePurchase = ReadHistoricRePurchase();

                historicRePurchase.LiquidationYear    = int.Parse(ddlYearOfSettlement.SelectedValue);
                historicRePurchase.PercentageApplied  = 5;
                historicRePurchase.Repurchase         = decimal.Parse(txtRepurchases.Text);
                historicRePurchase.TotalCreditCleared = decimal.Parse(txtTotalSettledClaims.Text);

                var oldHistoricRePurchase = bc.GetDetails(historicRePurchase.LiquidationYear);

                bc.Edit(historicRePurchase);
                
                var audit = new FrameworkManapro.Audit.Audit<HistoricRePurchase>
                {
                    EntityKey = oldHistoricRePurchase.LiquidationYear.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Update,
                    OldObject = oldHistoricRePurchase,
                    NewObject = historicRePurchase,
                    UserId    = ((User)Session["User"]).UserID
                };

                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<HistoricRePurchase>(audit);
                
                auditDAC.InsertAudit();

                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Historic Re-Purchase was successfully saved.", null);
                
                popupExtenderMessage.Show();
                
                Search();
                
                ClearFields();

                UpdateAvailableYears();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save Historic Re-Purchase", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Historic Re-Purchase couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }

        //-----------------------------------------------------
        
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible  = true;

            UpdateAvailableYears();

            ClearFields();
        }

        //-----------------------------------------------------
        
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvHistoricRePurchases.SelectedDataKey != null)
            {
                try
                {
                    var year = (int)this.grvHistoricRePurchases.SelectedDataKey.Value;
                    
                    var bc                 = new HistoricRePurchaseComponent();
                    var historicRePurchase = bc.GetDetails(year);

                    txtBolivaresTotalLiquidated.Text   = historicRePurchase.TotalBsCleared.val.ToString("N2");
                    txtRemnant.Text                    = historicRePurchase.Remnant.ToString("N2");
                    txtRepurchases.Text                = historicRePurchase.Repurchase.ToString("N2");
                    txtTotalAmountOfSettledClaims.Text = historicRePurchase.PercentClearedCredit.val.ToString("N2");
                    txtTotalSettledClaims.Text         = historicRePurchase.TotalCreditCleared.ToString("N2");

                    ddlYearOfSettlement.Items.Clear();
                    ddlYearOfSettlement.Items.Add(new ListItem(year.ToString(),year.ToString()));
                    ddlYearOfSettlement.SelectedIndex = 0;
                    ddlYearOfSettlement.Enabled       = false;

                    btnSave.Visible = true;
                    btnNew.Visible  = false;
                }
                catch (Exception ex)
                {
                    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Historic Re-Purchase", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                    wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the Historic Re-Purchase.", ex.ToString());
                    popupExtenderMessage.Show();
                }
            }
        }

        //-----------------------------------------------------
        
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvHistoricRePurchases.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A Historic Re-purchase must be selected.", null);
                
                popupExtenderMessage.Show();
            }
        }

        //-----------------------------------------------------
        
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new HistoricRePurchaseComponent();

                if (grvHistoricRePurchases.SelectedDataKey != null)
                {
                    var year               = (int)this.grvHistoricRePurchases.SelectedDataKey.Value;
                    
                    var historicRePurchase = new HistoricRePurchase
                    {
                        LiquidationYear    = year
                    };

                    var oldHistoricRePurchase = bc.GetDetails(historicRePurchase.LiquidationYear);

                    bc.Delete(oldHistoricRePurchase);

                    var audit = new FrameworkManapro.Audit.Audit<HistoricRePurchase>
                    {
                        EntityKey = historicRePurchase.LiquidationYear.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldHistoricRePurchase,
                        UserId    = ((User)Session["User"]).UserID
                    };
                    
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<HistoricRePurchase>(audit);
                    
                    auditDAC.InsertAudit();
                    
                    this.PagingControl.TotalRecords = Search();
                    
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Historic Re-Purchase was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }

                UpdateAvailableYears();

                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Historic Re-Purchase", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Historic Re-Purchase couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }
        }

        //-----------------------------------------------------
        
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            
            Search();
            
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            } 
            
            ClearFields();
        }
        
        #endregion

        ////////////////////////////////////////////////////////////////

        #region Other Events

        protected void grvHistoricRePurchases_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvHistoricRePurchases, "Select$" + e.Row.RowIndex);
                
            }
        }

        #endregion

        ////////////////////////////////////////////////////////////////

        #region Private Methods

        private void ClearFields()
        {
            txtBolivaresTotalLiquidated.Text   = string.Empty;
            txtRemnant.Text                    = string.Empty;
            txtRepurchases.Text                = string.Empty;
            txtTotalAmountOfSettledClaims.Text = string.Empty;
            txtTotalSettledClaims.Text         = string.Empty;
        }

        //-----------------------------------------------------

        private void Initialize()
        {
            try
            {
                var bc = new Business.Components.HistoricRePurchaseComponent();

                Years years = bc.GetListOfAllYears();

                this.ddlYearOfSettlementSearch.DataSource = years;

                this.ddlYearOfSettlementSearch.DataBind();

                UpdateAvailableYears();

                this.ddlYearOfSettlementSearch.Items.Insert(0, new ListItem("Select...", String.Empty));
 
                btnSave.Visible = false;
                btnNew.Visible  = true;
                
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected Historic Repurchase?", null);
                this.PagingControl.TotalRecords = Search();
				
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }

        //-----------------------------------------------------

        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("HistoricRePurchase");

            if (beEntities == null)
            {
                return;
            }
            
            if (!beEntities.CanRead)
            {
                this.grvHistoricRePurchases.Visible = false;

                btnModify.Visible                   = false;
                btnDelete.Visible                   = false;
                pnlSearch.Visible                   = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }

            if (!beEntities.CanInsert)
            {
                btnNew.Visible    = false;
                btnCancel.Visible = false;
                pnlEdit.Visible   = false;
            }

            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }

        //-----------------------------------------------------

        private int Search()
        {
            try
            {
                var  bc   = new Business.Components.HistoricRePurchaseComponent();
                int? year = (!this.ddlYearOfSettlementSearch.SelectedValue.Equals(string.Empty)) ? (int?)Convert.ToInt32(ddlYearOfSettlementSearch.SelectedValue) : null;

                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                
                paging.PageNumber    = this.PagingControl.PageNumber;
                paging.PageSize      = this.PagingControl.PageSize;
                paging.SortBy        = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;

                HistoricRePurchaseCollection historicRePurchases = bc.Search(year, paging);

                grvHistoricRePurchases.DataSource = historicRePurchases;

                grvHistoricRePurchases.DataBind();
                
                return historicRePurchases.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Historic Re-Purchase", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();

                return 0;
            }
        }

        //-----------------------------------------------------

        private HistoricRePurchase ReadHistoricRePurchase()
        {
            var historicRePurchase = new HistoricRePurchase();

            historicRePurchase.LiquidationYear      = int.Parse(ddlYearOfSettlement.SelectedValue);
            historicRePurchase.PercentageApplied    = 5;
            historicRePurchase.Repurchase           = decimal.Parse(txtRepurchases.Text);
            historicRePurchase.TotalCreditCleared   = decimal.Parse(txtTotalSettledClaims.Text);
            historicRePurchase.TotalBsCleared.val   = decimal.Parse(txtBolivaresTotalLiquidated.Text);

            return historicRePurchase;
        }

        //-----------------------------------------------------
        
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
             Search();
        }

        //-----------------------------------------------------

        protected void UpdateAvailableYears()
        { 
            var bc = new Business.Components.HistoricRePurchaseComponent();

            Years years = bc.GetListOfAvailableYears();

            ddlYearOfSettlement.DataSource = years;
            
            ddlYearOfSettlement.DataBind();

            this.ddlYearOfSettlement.Items.Insert(0, new ListItem("Select...", String.Empty));
            
            ddlYearOfSettlement.Enabled = true;
        }

        #endregion

        ////////////////////////////////////////////////////////////////

        #region Tests

        private DataTable GenerateDataTablePrueba()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("YearOfSettlement", typeof(string));
            dt.Columns.Add("TotalSettledClaims", typeof(string));
            dt.Columns.Add("BolivaresTotalLiquidated", typeof(string));
            dt.Columns.Add("Remnant", typeof(string));
            DataRow rowdt;
            rowdt = dt.NewRow();
            rowdt[0] = "1";
            rowdt[1] = "2007";
            rowdt[2] = "20";
            rowdt[3] = "4,302.78";
            rowdt[4] = "1,000";
            dt.Rows.Add(rowdt);
            
            return dt;

        }

        #endregion

    }
}
